package pl.engine.renderer.logic
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import pl.engine.model.IModel;
	import pl.error.InternalError;
	import pl.world.actors.proto.IActor;


	/**
	 * ...
	 * @author Bakudo
	 */
	public class LogicRenderer implements ILogicRenderer
	{
		private static var secure:Boolean;
		private var timer:Timer = new Timer( 50, 0 );
		private var model:IModel;
		private var actors:Vector.<IActor> = new Vector.<IActor>;
		private var actor:IActor;
		private var updateGraphicsHandler:Function;

		public function LogicRenderer( model:IModel )
		{
			if (secure == false) throw new Error( InternalError.CREATION_ERROR );
			this.model = model;
			timer.addEventListener( TimerEvent.TIMER, onTimerTick );
		}

		public static function factory( model:IModel ):ILogicRenderer
		{
			secure = true;
			return new LogicRenderer( model );
		}

		public function start():void
		{
			timer.start();
		}

		public function stop():void
		{
			timer.stop();
		}

		public function addActor( actor:IActor ):void
		{
			actors.push( actor );
		}

		public function getActors():Vector.<IActor>
		{
			return actors;
		}

		private function onTimerTick( e:TimerEvent ):void
		{
			var i:uint = 0;
			var n:uint = actors.length;
			var updateView:Boolean;
			while (i < n)
			{
				actor = (actors[i] as IActor);
				actor.processLogic();
				if (actor.updateView == true)
				{
					actor.updateView = false;
					updateView = true;
				}
				i++;
			}

			if (updateGraphicsHandler != null && updateView == true)
			{
				updateGraphicsHandler();
			}
		}

		public function setUpdateGraphicsHandler( handler:Function ):void
		{
			updateGraphicsHandler = handler;
		}
	}
}